/**
 * 用户注册 
 */
import query from '../../untils/mysql';
import * as uuid from 'uuid';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';
import { testing } from '../../untils/validator';

const validator = [
    check('phone').custom((val) => {
        if (!testing.isPhone(val)) {
            throw new Error('手机号格式有误');
        } else {
            return val
        }
    }),
    check('password').isLength({ min: 6, max: 16 }).withMessage('密码长度6-16位之间'),
    check('code').isLength({ min: 4, max: 6 }).withMessage('验证码长度输入有误').isNumeric().withMessage('验证码为数字'),
    check('name').notEmpty().withMessage("用户昵称不能为空").isLength({ min: 2, max: 20 }).withMessage('昵称长度2-20位之间'),
]
const POST = async (req: any, res: any, next: any) => {
    try {
        const { phone, password, code, name } = req.body;
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }
        const resname = await query(`select phone from user where name = '${name}'`);
        if (resname.length) {
            return Tip.tipError(res, '当前昵称已经存在');
        }

        // 查询手机号是否注册
        const resPhone = await query(`select phone from user where phone = '${phone}'`);
        if (resPhone.length) {
            return Tip.tipError(res, '当前手机号已经注册');
        }
        // 校验验证码
        const myCode = await query(`select * from code where phone = '${phone}'`);
        if (myCode.length === 0) {
            return Tip.tipError(res, '请发送验证码');
        }
        if (myCode[0].code !== code) {
            return Tip.tipError(res, '验证码输入有误');
        }
        // 注册账号
        const data = await query(`insert into user (id,phone,password,name) values ('${uuid.v1()}','${phone}','${password}','${name}')`);
        return Tip.tipSuccess(res, '注册成功', data)
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    POST,
    validator
}